import { ArrowRightOutlined } from '@ant-design/icons';
import { Card, Checkbox, Input, Space, Tree } from 'antd';
import type { CheckboxProps, TreeDataNode } from "antd";
import React, { useEffect, useImperativeHandle, useState, forwardRef, useMemo } from 'react';
import "./index.less";
import { getTreeItems, getUserAuthItem } from '@/services/demo/UserController';

type ExpandTree = { permission: boolean, list: ExpandTree[], children: ExpandTree[]; id: string; } & TreeDataNode;

// 后端需要目录类型，节点类型，dom类型
/**@description 根据permission映射树 */
const filterCheckedTree = (tree: ExpandTree[]) => {
  const temCheckedNodes: React.Key[] = [];
  function filterNodes(nodes: ExpandTree[]) {
    return nodes.reduce((filtered: any, node) => {
      node.permission && temCheckedNodes.push(node.id);
      if (node.permission || (node.children?.length > 0)) {
        const children = node.children ? filterNodes(node.children) : [];
        if (children.length || node.permission) {
          filtered.push({ ...node, children: children.length > 0 ? children : undefined });
        }
      }
      return filtered;
    }, []);
  }

  return { checkedNodes: temCheckedNodes, selectTree: filterNodes(tree) };
};

/**@description 转化后的一维数组 */
const dataList: ExpandTree[] = [];
const generateList = (data: ExpandTree[]) => {
  for (let i = 0; i < data.length; i++) {
    const node = data[i];
    // 保持引用
    dataList.push(node);
    if (node.children) {
      generateList(node.children);
    }
  }
};

/**@description 获取最上层父节点 */
const getParentKey = (id: React.Key, tree: ExpandTree[]): React.Key => {
  let parentKey: React.Key;
  for (let i = 0; i < tree.length; i++) {
    const node = tree[i];
    if (node.children) {
      if (node.children.some((item) => item.id === id)) {
        parentKey = node.id;
      } else if (getParentKey(id, node.children)) {
        parentKey = getParentKey(id, node.children);
      }
    }
  }
  return parentKey!;
};
const getElementIds = (tree: ExpandTree[], ids: string[] = [], pageIds: string[] = []) => {
  for (let i = 0; i < tree.length; i++) {
    const child = tree[i].children || tree[i].list;
    if (child) {
      pageIds.push(tree[i].id);
      getElementIds(child, ids, pageIds);
    } else {
      if (tree[i].permission) {
        ids.push(tree[i].id);
      }
    }
  }
  return { ids, pageIds };
};

export default forwardRef(function Empower(props: { type: "role" | "basic", role?: string; disabled: boolean, menu?: boolean }, ref) {
  const [searchValue, setSearchValue] = useState('');
  const [searchSeValue, setSeSearchValue] = useState('');
  const [searchDoValue, setDoSearchValue] = useState('');
  const [treeData, setTreeData] = useState<ExpandTree[]>([]);
  const [selectTreeData, setSelectTreeData] = useState<ExpandTree[]>([]);

  const [expandedKeys, setExpandedKeys] = useState<React.Key[]>([]);
  const [selectExpandedKeys, setSelectExpandedKeys] = useState<React.Key[]>([]);
  const [checkedKeys, setCheckedKeys] = useState<React.Key[]>([]);
  const [selectedKeys, setSelectedKeys] = useState<React.Key[]>([]);
  const [autoExpandParent, setAutoExpandParent] = useState<boolean>(true);
  const [domOptions, setDomOptions] = useState<ExpandTree[]>([]);

  const [indeterminate, setTndeterminate] = useState(false);
  const [checkAll, setCheckAll] = useState(false);

  useEffect(() => {
    console.log(1);
    const method = props.type === "role" ? getUserAuthItem : getTreeItems;
    method(props.role).then(res => {
      const result = props.type === "role" ? res.result.roleTree : res.result;
      console.log(res);
      setDomOptions([]);
      setSelectedKeys([]);
      setExpandedKeys([])
      setSelectExpandedKeys([])
      setTreeData(result);

      const { selectTree, checkedNodes } = filterCheckedTree(result);
      setSelectTreeData(selectTree);
      setCheckedKeys(checkedNodes);
      console.log("xxxxxxxxxx", checkedNodes, result);

      //treedata保持引用
      generateList(result);

    });
    // getTreeItems(props.role).then(res => {
    //   setTreeData(res.result);

    //   const { selectTree, checkedNodes } = filterCheckedTree(res.result);
    //   setSelectTreeData(selectTree);
    //   setCheckedKeys(checkedNodes);
    //   console.log("xxxxxxxxxx", checkedNodes, res.result);

    //   //treedata保持引用
    //   generateList(res.result);
    // });
  }, [props.role]);
  const onExpand = (expandedKeysValue: React.Key[], type = 1) => {
    console.log('onExpand', expandedKeysValue);
    console.log(type);

    type == 1 ? setExpandedKeys(expandedKeysValue) : setSelectExpandedKeys(expandedKeysValue);
    setAutoExpandParent(false);
  };
  useMemo(() => {

    const count = domOptions.reduce((op1, op2) => {
      return op1 + Number(op2.permission);
    }, 0);
    setTndeterminate(count > 0 && count < domOptions.length);
    setCheckAll(count == domOptions.length);
  }, [domOptions]);
  const onCheck = (checkedKeysValue: any) => {
    console.log('onCheck', checkedKeysValue);
    setCheckedKeys(checkedKeysValue);
    // 修改对应节点权限
    dataList.forEach(item =>
      item.permission = checkedKeysValue.includes(item.id));
    const { selectTree, checkedNodes } = filterCheckedTree(treeData);
    if (!checkedKeysValue.includes(selectedKeys[0])) {
      setDomOptions([]);
      setSelectedKeys([]);
    }
    setSelectTreeData(selectTree);
  };

  const onSelect = (selectedKeysValue: React.Key[], info: any) => {
    console.log(info.node.list);
    if (info.node.list) {
      setDomOptions(info.node.list);
      setSelectedKeys(selectedKeysValue);
    }
  };

  /**@description 搜索页面 */
  const onPageSearch = (e: React.ChangeEvent<HTMLInputElement>, type = 1) => {
    const { value } = e.target;

    const newExpandedKeys = dataList
      .map((item) => {
        if ((item.title as string).indexOf(value) > -1) {
          return getParentKey(item.id, type == 1 ? treeData : selectTreeData);
        }
        return null;
      })
      .filter((item, i, self): item is React.Key => !!(item && self.indexOf(item) === i));
    console.log(newExpandedKeys);

    if (type == 1) {
      setExpandedKeys(newExpandedKeys);
      setSearchValue(value);
    } else {
      setSelectExpandedKeys(newExpandedKeys);
      setSeSearchValue(value);
    }
    setAutoExpandParent(true);

  };

  /**@description 搜索页面元素 */
  const onDomSearch = (e: React.ChangeEvent<HTMLInputElement>) => {
    setDoSearchValue(e.target.value);
  };
  const onDomChange: CheckboxProps["onChange"] = (e => {
    function findList(children: ExpandTree[]) {
      children.forEach(child => {
        if (child.id === selectedKeys[0]) {
          child.list.forEach(li => {
            console.log(li, e.target.value);

            li.id === e.target.value && (li.permission = e.target.checked);
          });
          setDomOptions(child.list);
          return;
        } else if (child.children?.length) {
          findList(child.children);
        }
      });
    }
    const deepSelectData = JSON.parse(JSON.stringify(selectTreeData));
    findList(deepSelectData);
    console.log(selectTreeData, deepSelectData);
    setSelectTreeData(deepSelectData);
  });

  const onCheckAllChange: CheckboxProps['onChange'] = (e) => {

    function findList(children: ExpandTree[]) {
      children.forEach(child => {
        if (child.id === selectedKeys[0]) {
          child.list.forEach(li => li.permission = e.target.checked);
          setDomOptions(child.list);
          return;
        } else if (child.children?.length) {
          findList(child.children);
        }
      });
    }
    const deepSelectData = JSON.parse(JSON.stringify(selectTreeData));
    findList(deepSelectData);
    setSelectTreeData(deepSelectData);
  };
  // const filterDom = () => {
  //   console.log(domOptions.filter(dom => (dom.title as string).includes(searchDoValue)));

  //   return domOptions.filter(dom => (dom.title as string).includes(searchDoValue));
  // };
  const filterDom = useMemo(() => {
    console.log(domOptions.filter(dom => (dom.title as string).includes(searchDoValue)));

    return domOptions.filter(dom => (dom.title as string).includes(searchDoValue));
  }, [domOptions]);
  /**@description 标记选中颜色 */
  const loop = (data: TreeDataNode[], type: 1 | 2): TreeDataNode[] => {
    const ss = type == 1 ? searchValue : searchSeValue;
    return data.map((item) => {
      const strTitle = item.title as string;
      const index = strTitle.indexOf(ss);
      const beforeStr = strTitle.substring(0, index);
      const afterStr = strTitle.slice(index + ss.length);
      const title =
        index > -1 ? (
          <span>
            {beforeStr}
            <span className="site-tree-search-value">{ss}</span>
            {afterStr}
          </span>
        ) : (
          <span>{strTitle}</span>
        );
      if (item.children) {
        return { ...item, title, children: loop(item.children, type) };
      }

      return {
        ...item,
        title,

      };
    });
  }
    ;
  useImperativeHandle(ref, () => ({ finish }));
  const finish = () => {
    const { ids, pageIds } = getElementIds(selectTreeData)
    return { elementIds: ids, menuIds:  pageIds };

  };
  return <div className="empower_item" >
    <Card>
      <Space className='search_block'>
        <span className='search_label'>选择页面：</span>
        <Input.Search placeholder='快速定位' onChange={(e) => onPageSearch(e, 1)} />
      </Space>
      <Tree
        disabled={props.disabled}
        checkable
        onExpand={(e) => onExpand(e, 1)}
        expandedKeys={expandedKeys}
        autoExpandParent={autoExpandParent}
        onCheck={onCheck}
        checkedKeys={checkedKeys}
        // onSelect={onSelect}
        // selectedKeys={selectedKeys}
        fieldNames={{ title: "title", key: "id", children: "children" }}
        treeData={loop(treeData, 1)}
      />
    </Card>
    <ArrowRightOutlined />
    <Card>
      <Space className='search_block'>
        <span className='search_label'>已选中页面：</span>
        <Input.Search placeholder='快速定位' onChange={(e) => onPageSearch(e, 2)} /></Space>
      <Tree
        disabled={props.disabled}
        onExpand={(e) => onExpand(e, 2)}
        expandedKeys={selectExpandedKeys}
        autoExpandParent={autoExpandParent}
        // onCheck={onCheckDom}
        selectedKeys={selectedKeys}
        onSelect={onSelect}
        treeData={loop(selectTreeData, 2)}
        fieldNames={{ title: "title", key: "id", children: "children" }}
      />
    </Card>
    <ArrowRightOutlined />
    <Card>
      <Space className='search_block'>
        <span className='search_label'>页面元素配置：</span>
        <Input.Search placeholder='快速定位' onChange={onDomSearch} />
      </Space>
      <Checkbox checked={checkAll} indeterminate={indeterminate} onChange={onCheckAllChange} >
        全选
      </Checkbox>
      <div>
        {filterDom.map((dom: ExpandTree) => <div key={dom.id}><Checkbox onChange={onDomChange} checked={dom.permission} value={dom.id}>{dom.title as string}</Checkbox></div>)}
      </div>
    </Card>
  </div>;
});
